<?php
namespace config\lib;

class Response
{
    //原始数据
    protected $data;

    //当前的contentType
    protected $contentType = 'text/hrml';

    // 字符集
    protected $charset = 'utf-8';

    //状态
    protected $code = 200;

    //输出参数
    protected $option = [];
    //header参数
    protected $header = [];

    protected $content = [];

    //初始化
    public function __construct($data = '',$code = 200,array $header = [],array $option = [])
    {
        if (!empty($options)) {
            $this->option = array_merge($this->option,$option);
        }
        $this->header = array_merge($this->header, $header);
        $this->code = $code;
    }

    //创建实例
    public static function create($data = '',$type = '',$code = 200,array $header = [],array $option = [])
    {
        $class = false !== strpos($type,'\\') ? $type : '\\coser\\response\\' . ucfirst(strtolower($type));

        //if( class_exists($class)){
        //    $response = new $class($data,$code,$header,$option);
        //}else{
        $response = new static($data,$code,$header,$option);
        //}
        return $response;
    }

    //发生数据
    public function send()
    {
        // 处理输出数据
        $data = $this->getContent();

        //设置header
        $this->header['Cache-Control'] = 'max-age=' . 60 . ',must-revalidate';
        $this->header['Last-Modified'] = gmdate('D, d M Y H:i:s') . ' GMT';
        $this->header['Expires']       = gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME'] + 60) . ' GMT';

        if (!headers_sent() && !empty($this->header)) {
            // 发送状态码
            http_response_code($this->code);
            // 发送头部信息
            foreach ($this->header as $name => $val) {
                if (is_null($val)) {
                    header($name);
                } else {
                    header($name . ':' . $val);
                }
            }
        }

        echo $data;

        if (function_exists('fastcgi_finish_request')){
            fastcgi_finish_request();
        }
    }

    //输出数据设置
    public function data($data)
    {
        $this->data = $data;
        $this->$data = $data;
        return $this;
    }

    //处理数据
    protected function output($data)
    {
        return $data;
    }

    //获取输出数据
    public function getContent()
    {
        if (null == $this->content) {
            $content = $this->output($this->data);
            $this->content = (string) $content;
        }
        return $this->content;
    }

    // 设置页面输出内容
    public function content($content)
    {
        $this->content = (string) $content;

        return $this;
    }
}